import { Router } from "express";
import { AuthMiddleware } from "../../core/middleware/auth.js";
import { UploadMiddleware } from "../../core/middleware/upload.middleware.js";
import { FileUploadController } from "./controller.js";
import { errorHandler } from "../../core/middleware/errorHandler.js";
import {
  uploadFileSchema,
  initChunkUploadSchema,
  uploadChunkSchema,
  mergeChunksSchema,
} from "./schema.js";
import { API_URLS } from "../../config/api-urls.js";

const router = Router();

// 单文件上传
router.post(
  API_URLS.UPLOAD_FILE,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  UploadMiddleware.single("file"),
  UploadMiddleware.createFileRecord, // 新增
  AuthMiddleware.validate(uploadFileSchema),
  FileUploadController.uploadFile
);

// 上传缩略图资源
router.post(
  API_URLS.UPLOAD_THUMBNAIL,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  UploadMiddleware.single("file", 'thumbnails'),
  UploadMiddleware.createFileRecord, // 新增
  AuthMiddleware.validate(uploadFileSchema),
  FileUploadController.uploadThumbnail
);

// 上传详情图资源
router.post(
  API_URLS.UPLOAD_GALLERY,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  UploadMiddleware.multiple("images", 'products'),
  UploadMiddleware.createFileRecord, // 新增
  AuthMiddleware.validate(uploadFileSchema),
  FileUploadController.uploadGallery
);

// 上传商品SKU图
router.post(
 API_URLS.UPLOAD_SKU,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  UploadMiddleware.single("file", 'skus'),
  UploadMiddleware.createFileRecord, // 新增
  AuthMiddleware.validate(uploadFileSchema),
  FileUploadController.uploadSku
);

// 文件列表
router.get(
  API_URLS.GET_FILES_LIST,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  FileUploadController.getFilesList
);

// 分片上传初始化
router.post(
  API_URLS.UPLOAD_CHUNK_INIT,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  AuthMiddleware.validate(initChunkUploadSchema),
  FileUploadController.initChunkUpload
);

// 上传分片
router.post(
  API_URLS.UPLOAD_CHUNK,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  UploadMiddleware.single("chunk", 'chunks'),
  AuthMiddleware.validate(uploadChunkSchema),
  FileUploadController.uploadChunk
);

// 合并分片
router.post(
  API_URLS.UPLOAD_MERGE,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  AuthMiddleware.validate(mergeChunksSchema),
  FileUploadController.mergeChunks
);

// 删除文件
router.delete(
  API_URLS.UPLOAD_DELETE,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  FileUploadController.deleteFile
);


// 获取上传进度
router.get(
  "/upload/progress/:uploadId",
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  FileUploadController.getUploadProgress
);

// 检测文件是否存在
router.get(
  API_URLS.UPLOAD_VERIFY,  
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  FileUploadController.checkFileExists
);

// 错误处理
router.use(errorHandler);

export default router;
